<template lang="pug">
  el-drawer.commonDrawer(
    title="线索转客户"
    :visible="visibleDialog"
    append-to-body
    direction="rtl"
    size="720px"
    @close="$_handleCancel"
  )
    .drawer-content
      form-box(
        ref="form"
        :fields="fields"
        :showBtns="false"
        :layoutCol="{ xs: 12, md: 12, lg: 12 }"
      )
        el-button(slot="form-product" type="primary" icon="el-icon-circle-plus" round @click="addEdit") 添加产品
      s-table(
        ref="productTable"
        :column="productColumn2"
        :dataPops="productRecords"
      )
        p.mt16(slot="sumBox")
          span 预计销售收入:
          el-link(type="danger" :underline="false")
            small ￥
            b.f18 {{productSum}}
        template(slot="count" slot-scope="text, scope")
          el-input-number.w(:value="text" controls-position="right" :min="1" @change="val => productFormChange(val, scope.id, 'count')")
        template(slot="amount" slot-scope="text, scope") {{scope.standardAmount * (scope.count || 1)}}
        template(slot="remark" slot-scope="text, scope")
          el-input.w(:value="text" controls-position="right" @input="val => productFormChange(val, scope.id, 'remark')")
        template(slot="action" slot-scope="text, scope")
          el-link(@click="deleteProductHandle(scope.id)" type="primary") 删除
    .drawer-footer.tr
      el-button.gradientVertical(size="large" :loading="submitting" @click="submitHandle" round) 确定
    product-table(ref="productTableRef" @getProductData="addProductData" :value="productRecords")
</template>
<script>
import { mapGetters } from 'vuex'
import { regs } from '@/utils/validate'
import { toClientSubmit } from '../api'
import productTable from '../tabs/product/productTable'

const productColumn2 = [
  {
    label: '产品名称',
    prop: 'name'
  },
  {
    label: '标准单价',
    prop: 'standardAmount'
  },
  {
    label: '销售单位',
    prop: 'unit'
  },
  {
    label: '意向数量',
    prop: 'count',
    width: '140'
  },
  {
    label: '总价',
    prop: 'amount'
  },
  {
    label: '备注',
    prop: 'remark',
    width: '140'
  },
  {
    label: '操作',
    prop: 'action'
  }
]

export default {
  components: {
    productTable
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: ''
    },
    info: {
      type: Object,
      default: () => ({})
    },
    id: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      submitting: false,
      productColumn2,
      products: [],
      productRecords: [] // 意向产品
    }
  },
  computed: {
    ...mapGetters(['curArea']),
    visibleDialog: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    },
    // 计算意向产品总金额
    productSum () {
      const { productRecords } = this
      return productRecords.reduce((sum, cur) => {
        return sum + (cur.standardAmount || 0) * (cur.count || 1)
      }, 0)
    },
    fields () {
      const { info } = this
      return [
        {
          label: '孩子姓名',
          key: 'sysChildName',
          rules: [{ required: true, message: '请输入' }],
          initialValue: info.childName
        },
        {
          label: '性别',
          key: 'gender',
          type: 'select',
          initialValue: info.gender?.toString(),
          fieldProps: {
            dictKey: 'sex',
            props: { value: 'value', label: 'label' }
          }
        },
        {
          label: '出生年月',
          key: 'birthday',
          type: 'date',
          formatFlag: true,
          initialValue: info.birthday
        },
        {
          label: '家长姓名',
          key: 'clienteleName',
          rules: [{ required: true, message: '请输入' }],
          initialValue: info.name
        },
        {
          label: '联系电话',
          key: 'mobile',
          rules: [{ required: true, message: '请输入手机号码' }, { max: 11, pattern: regs.phone, message: '请输入正确的手机号码!' }],
          initialValue: info.mobile
        },
        {
          label: '客户分类',
          key: 'clienteleType',
          type: 'select',
          disabled: true,
          fieldProps: {
            dictKey: 'clienteleType'
          }
        },
        {
          label: '意向产品',
          key: 'product',
          type: 'slot'
        }
      ]
    }
  },
  created () {
  },
  methods: {
    // 选择意向产品
    addProductData (data) {
      const list = data.map(x => {
        x.count = 1
        return x
      })
      this.addProductRecords(list)
      this.productVisible = false
    },
    addProductRecords (data) {
      const list = data.filter(value => {
        let flag = true
        for (const index in this.productRecords) {
          const item = this.productRecords[index]
          if (item.id === value.id) {
            flag = false
          }
        }
        return flag
      })
      this.productRecords = [...this.productRecords, ...list]
    },

    productFormChange (val, id, key) {
      const { productRecords } = this
      this.productRecords = productRecords.map(x => {
        if (x.id === id) {
          x[key] = val
        }
        return x
      })
    },
    // 删除选中意向产品
    deleteProductHandle (id) {
      const { productRecords } = this
      this.productRecords = productRecords.filter(x => x.id !== id)
    },
    // 转客户
    async submitHandle () {
      const { curArea, id, productRecords, type } = this
      const values = await this.$refs.form.submitForm()
      delete values.product
      toClientSubmit({ areaId: curArea.areaId }, {
        ...values,
        leadsId: id,
        productRecords: JSON.stringify(productRecords.map(x => {
          return {
            productId: x.id,
            count: x.count,
            remark: x.remark || ''
          }
        }))
      }).then(() => {
        this.$message('提交成功')
        if (type === 'clue') {
          this.$router.go(-1)
        } else {
          this.$emit('getInfo')
          this.$_handleCancel()
        }
      })
    },
    $_handleCancel () {
      this.visibleDialog = false
    },

    addEdit () {
      this.$refs.productTableRef.mainFun()
    }
  }
}
</script>
